var ver_code=null;
var std_year_old=null;
var group_type=null;
var std_type=null;
var strold='';
var strnew='';
var quotaCodes;
var loadflag_1=0, loadflag_2=0, loadflag_3=0, loadflag_4=0;
$(function(){
	showCondition(true,0,0,1,[]);	
	var param=drgUI.setAjaxData(tabId);
	strold='<table id="dep_monitor_old" class="table display nowrap" cellspacing="0" width="100%" role="grid" aria-describedby="example_info" style="width: 100%;">';
	strold +='<caption class="contaotalsccq" style="text-align:center;">指标历史值查询结果</caption>';
	strold +=' <thead>  <tr></tr> </thead> <tbody></tbody>';
	strold +='</table>';
	$('#'+tabId+ ' #dep_monitor_old_div').html(strold);
	
    strnew='<table id="dep_monitor_new" class="table display nowrap" cellspacing="0" width="100%" role="grid" aria-describedby="example_info" style="width: 100%;">';
	strnew +='<caption class="contaotalsccq" style="text-align:center;">指标最新值查询结果</caption>';
	strnew +=' <thead>  <tr></tr> </thead> <tbody></tbody>';
	strnew +='</table>';
	$('#'+tabId+ ' #dep_monitor_new_div').html(strnew);
	$.post(contextPath + "/monitorHistory/getHisGroupVersion.dhc",param).done(function(result){
		if(result.success && result.data && result.data.length>0){
			var data=result.data;
			$CommonUI.combobox($("#" + tabId + " #group_version_id"), data,
				    "VER_DESC", "VER_CODE", {
					"height" : 31,//设定框的高度
					"onSelect" : function(n, o) {
						ver_code=$("#"+tabId+" #group_version_id").combobox('getValue');
					},
					"onLoadSuccess" : function(){ 
						var data = $("#"+tabId+" #group_version_id").combobox('getData');
						if(data.length>0){
							$("#"+tabId+" #group_version_id").combobox('select',data[0].VER_CODE);
							ver_code=$("#"+tabId+" #group_version_id").combobox('getValue');
							loadflag_1=1;
						}
					}  
				});
		}else{		
			var data=[{"VER_CODE":"","VER_DESC":"无历史数据"}];
			$CommonUI.combobox($("#" + tabId + " #group_version_id"), data,
				    "VER_DESC", "VER_CODE", {
					"height" : 31,//设定框的高度
					"onSelect" : function(n, o) {
						ver_code=$("#"+tabId+" #group_version_id").combobox('getValue');
					}
			});
			loadflag_1=1;
		}
	});
	$.post(contextPath + "/monitorHistory/getStdYear.dhc",{}).done(function(result){
		if(result.success && result.data && result.data.length>0){
			var data=result.data;
			 $CommonUI.combobox($("#" + tabId + " #std_year_id"), data,
				    "STD_YEAR", "STD_YEAR", {
					"height" : 31,//设定框的高度
					"onSelect" : function(n, o) {
						std_year_old=$("#"+tabId+" #std_year_id").combobox('getValue');
					},
					"onLoadSuccess" : function(){ 
						var data = $("#"+tabId+" #std_year_id").combobox('getData');
						if(data.length>0){
							$("#"+tabId+" #std_year_id").combobox('select',data[0].STD_YEAR);
							std_year_old=$("#"+tabId+" #std_year_id").combobox('getValue');
							loadflag_2=1;
						}
					}  
				});
		}else{
			 $CommonUI.combobox($("#" + tabId + " #std_year_id"), data,
					    "STD_YEAR", "STD_YEAR", {
						"height" : 31,//设定框的高度
			 });
			loadflag_2=1;
		}
	});
	$.post(contextPath + "/monitorHistory/getStdType.dhc",{}).done(function(result){
		if(result.success && result.data && result.data.length>0){
			var data=result.data;
			$CommonUI.combobox($("#" + tabId + " #std_type"), data,
				    "DIC_DESC","AS_STD_TYPE", {
					"height" : 31,//设定框的高度
					"onSelect" : function(n, o) {
						std_type=$("#"+tabId+" #std_type").combobox('getValue');
					},
					"onLoadSuccess" : function(){ 
						var data = $("#"+tabId+" #std_type").combobox('getData');
						if(data.length>0){
							$("#"+tabId+" #std_type").combobox('select',data[0].AS_STD_TYPE);
							std_type=$("#"+tabId+" #std_type").combobox('getValue');
							loadflag_3=1;
						}
					}  
				});
		}else{
			$CommonUI.combobox($("#" + tabId + " #std_type"), data,
				    "DIC_DESC","AS_STD_TYPE", {
					"height" : 31,//设定框的高度
			});
			loadflag_3=1;
		}
	});
	//分组方案
	var data=[{"VERTYPE_CODE":"BJ","VERTYPE_DESC":"北京版"},{"VERTYPE_CODE":"CN","VERTYPE_DESC":"CC版"}];
	$CommonUI.combobox($("#" + tabId + " #group_version_scheme"), data,
	    "VERTYPE_DESC","VERTYPE_CODE", {
		"height" : 31,//设定框的高度
		"onSelect" : function(n, o) {
			group_type=$("#"+tabId+" #group_version_scheme").combobox('getValue');
		},
		"onLoadSuccess" : function(){ 
			var data = $("#"+tabId+" #group_version_scheme").combobox('getData');
			if(data.length>0){
				$("#"+tabId+" #group_version_scheme").combobox('select',data[0].VERTYPE_CODE);
				group_type=$("#"+tabId+" #group_version_scheme").combobox('getValue');
			}
			loadflag_4=1;
		}  
	});
	/**
	 * 等待查询条件加载完毕
	 */
	var timerId = setInterval(function(){
		if(loadflag_1==1 && loadflag_2==1 && loadflag_3==1 && loadflag_4==1){
			clearInterval(timerId);
			getQuotas("monitorHistory");
		}
	}, 500)
	//历史数据查询
	$('#'+tabId+' #hisSearch').on('click',function(){
		if(ver_code!=null){
			loadHistoryQuotas(quotaCodes,"dep_monitor_old", "1");
		}
	});
});

/**
 * @ Discription:获取当前数据
 * @Autor ：liuhongjun
 * @Date  ：2018年5月4日下午10:47:23
 */
function getQuotas(pageCode){
	$.post(contextPath + "/quota/getQuotas.dhc", {pageCode: pageCode}).done(function(data){
		if(data.data.length==0) {
			drgUI.error('没有配置指标,请联系管理员');
		}
		var totalQuota = arrayToTree(data.data, "id", "pid");
		var zTrees = $.extend(true, [], totalQuota);
		totalQuota = getQuotaData(totalQuota);
		loadData(totalQuota);
		loadQuotaSettings(pageCode, zTrees, totalQuota);
	});
}

/**
 * @ Discription:加载数据
 * @Autor ：liuhongjun
 * @Date  ：2018年4月8日上午9:46:51
 */
function loadData(totalQuota){
	quotaCodes=totalQuota;
	if(ver_code==null){
		loadHistoryQuotas(totalQuota,"dep_monitor_new", "0");	
	}else{
		loadHistoryQuotas(totalQuota,"dep_monitor_old", "1");
		loadHistoryQuotas(totalQuota,"dep_monitor_new", "0");
	}
}

function loadQuotaSettings(pageCode, zTrees, totalQuota){
	var quotaSettingBtn = $('<div class="btn-clickable" style="margin:2px;">指标配置<i class="fa fa-cog fa-lg"></i></div>');
	$("#"+tabId+" #hosp-ul").before(quotaSettingBtn);
	quotaSettingBtn.bind("click", function(){
		$.post(contextPath+"/pages/common/quota-tree.jsp").done(function(data){
			var dialog  = $(data);
			dialog.find(".modal-title").html("指标配置选项");
			var str = '';
			str += '<div class="zTreeDemoBackground">';
			str += '<ul id="treeDemo" class="ztree"></ul>';
			str += '</div>"';
			dialog.find(".echartscq").html(str);
			
			var setting = {
					view: {
						selectedMulti: false
					},
					check: {
						enable: true
					},
				};
			$.fn.zTree.init(dialog.find("#treeDemo"), setting, zTrees);
			dialog.find('#save').on('click', function(){
				dialog.find('#save').attr("disabled", "");
				var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				zTrees = zTree.getNodes();
				var nodes =  $.extend(true, [], zTrees);
				totalQuota = getQuotaData(nodes);
				var zTreeSimp = zTree.transformToArray(zTrees);
				var ajaxCount = zTreeSimp.length;
				var ajaxS = 0;
				var errorLog;
				for(var o in zTreeSimp){
					var node = zTreeSimp[o];
					node.pageCode = pageCode;
					$.post(contextPath + "/quota/saveQuotas.dhc", {param: JSON.stringify(node)}).done(function(data){
						ajaxS ++;
						if(!data.success){
							errorLog += "指标("+node.code+")报错\n"+data.errorMessage;
							errorLog += "\n";
						}
					})
				}
				var timer = setInterval(function(){
					if(ajaxS == ajaxCount){
						clearInterval(timer);
						if(errorLog){
							dialog.modal('hide');
							drgUI.error(errorLog) ;
						}else{
							dialog.trigger('complete');
						}
						
					}
				}, 500);
			}).end().modal({
				keyboard : false
			}).on({
				'hidden.bs.modal' : function() {
					dialog.remove();
				},
				'complete' : function() {
					dialog.modal('hide');
					loadData(totalQuota);
	            }
			});
		})
	});
}
/**
 * 
 * @author ：LiuHongjun
 * @any
 * @Discription:获取历史数据和当前数据
 * @monitorHistory.js
 */
function loadHistoryQuotas(totalQuota, divId, isHistory){
	//获取监测指标
	var newQuotas = [];
	getThisQuotas(totalQuota);
	function getThisQuotas(quotas){
		for(var o in quotas){
			var quota = quotas[o];
			if(quota.children){
				getThisQuotas(quota.children);
			}else{
				newQuotas.push(quota)
			}
		}
	};
	var datas = [];
	getTableData("Base", "hosp", isHistory, function(quotaCode,monitorType,isHistory,data){
		datas = datas.concat(data);		
		getTableData("Base", "dep", isHistory, function(quotaCode,monitorType,isHistory,data){
			datas = datas.concat(data);
				if(divId=="dep_monitor_old"){
					$('#' + tabId + ' #dep_monitor_old').remove();
					$('#'+tabId+ ' #dep_monitor_old_div').html(strold);
				}else{
					$('#' + tabId + ' #dep_monitor_new').remove();
					$('#'+tabId+ ' #dep_monitor_new_div').html(strnew);
				}
				concatTableData(newQuotas, datas, divId, isHistory);
		
		})
	});
}

/**
 * @ Discription:创建新表格
 * @Autor ：liuhongjun
 * @Date  ：2018年4月8日上午10:11:35
 */
function concatTableData(newQuotas, datas, divId, isHistory){
	if(newQuotas.length==0){
		return;
	}
	var thead = $("#"+tabId+" #"+divId+" thead tr");
	thead.html("");
	thead.append("<td>科室</td>");
	//拼接表头
	for(var o in newQuotas){
		var quota = newQuotas[o];
		thead.append("<td>"+quota.name+"</td>");
	}
	var columns = [ 
                   {  "data": "ccode", 
                      "render": function(obj, type, full) {
                   	return full.ddesc;
              	 	 	}
                    }
                ];
	//拼接表格列属性
	for(var o in newQuotas){
		var quota = newQuotas[o];
		columns.push({ "data": quota.code});
	}
	
	//获取配置指标数据
	var ajaxCount = newQuotas.length;
	for(var o in newQuotas){
		var quota = newQuotas[o];
		getQuotaData(quota.code);
	}
	/**
	 * 获取表格数据
	 */
	function getQuotaData(quotaCode){
		getTableData(quotaCode, "hosp", isHistory, function(quotaCodecall,monitorTypecall,isHistorycall,datacall){
			var data_s = [];
			data_s = data_s.concat(datacall);
			getTableData(quotaCodecall, "dep", isHistorycall, function(quotaCodecall,monitorTypecall,isHistorycall,datacall){
				data_s = data_s.concat(datacall);
				ajaxCount--;
				mergeList(datas, data_s,'ccode');
			});
		})
	}
	
	var timer = setInterval(function(){
		if(ajaxCount==0){
			clearInterval(timer);
			drawTable(datas, columns, divId);
		}
	}, 500);
};
/**
 * 绘制表格
 * @param {} data
 * @param {} columns
 * @param {} divId
 * @param {} isHistory
 */
function drawTable(data, columns, divId, isHistory){
	var paramsDataTables={info:false,scrollX:true,rownumbers:true,order:[]};
	$("#"+tabId+" #"+divId).dataTableBasic(columns,data,paramsDataTables);
}
/**
 * 获取表格数据
 * @param {} quotaCode
 * @param {} monitorType
 * @param {} isHistory
 * @param {} callback
 */
function getTableData(quotaCode, monitorType, isHistory, callback){
	var std_id;
	var gver_code;
	var ver_region;
	if(isHistory!='1'){
		gver_code=null;
		std_id=null;
		ver_region = null;
	}else{
		gver_code=ver_code;
		std_id=ver_code+"_"+std_type+"_"+std_year_old;
		ver_region = group_type;
	}
	var param=drgUI.setAjaxData(tabId);
	param.monitorType=monitorType;
	param.quotaCode=quotaCode;
	param.isGetCc='0';
	param.isHistory=isHistory;
	param.stdId=std_id;
	param.verCode=gver_code;
	param.verRegion=ver_region;
	$.post(contextPath + "/monitorHistory/findMonitorHistory.dhc",param
		).done(function(result){
			var data=[];
			if(result.success&& result.data && result.data.length>0){
				var data = result.data;
			}
			callback(quotaCode,monitorType,isHistory,data);
		});
}
